package com.shop.dao.user;

import com.shop.dao.BaseDao;
import com.shop.pajo.LoginTicket;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginTicketDaoImpl implements LoginTicketDao{

    @Override
    public int addLoginTicket(Connection connection,  LoginTicket loginTicket) throws SQLException {
        PreparedStatement preparedStatement = null;
        int addNum = 0;

        if(connection != null) {
            String sql = "insert into login_ticket(uid,status,ticket,expired) " +
                    "values(?,?,?,?)";
            Object[] params = {loginTicket.getUserId(),loginTicket.getStatus(),loginTicket.getTicket(),loginTicket.getExpired()};
            addNum = BaseDao.execute(connection, preparedStatement, sql, params);

            BaseDao.closeResource(null, preparedStatement, null);
        }
        return addNum;
    }

    @Override
    public LoginTicket getLoginTicketByTicket(Connection connection, String ticket) throws SQLException {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        LoginTicket loginTicket = null;

        if(connection != null) {
            String sql = "select * from login_ticket where ticket=?";
            Object[] params = {ticket};

            resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql, params);

            while (resultSet.next()) {
                loginTicket = new LoginTicket();
                loginTicket.setId(resultSet.getInt("id"));
                loginTicket.setUserId(resultSet.getInt("uid"));
                loginTicket.setStatus(resultSet.getInt("status"));
                loginTicket.setTicket(resultSet.getString("ticket"));
                loginTicket.setExpired(resultSet.getDate("expired"));
            }
            BaseDao.closeResource(null, preparedStatement, resultSet);
        }

        return loginTicket;
    }

    @Override
    public int updateStatus(Connection connection, String ticket, int status) throws SQLException {
        PreparedStatement preparedStatement = null;
        int updateNum = 0;

        if(connection != null) {
            String sql = "update login_ticket set status=? where ticket=?";
            Object[] params = {status, ticket};
            updateNum = BaseDao.execute(connection, preparedStatement, sql, params);

            BaseDao.closeResource(null, preparedStatement, null);
        }
        return updateNum;
    }
}
